import { defineStore } from 'pinia'
import { reactive } from 'vue'
import type { MovieUploadForm } from '../composables/movies/types'

export interface MovieFormDraftData {
  form: MovieUploadForm
  coverPreview?: string
  originalCoverUrl?: string
}

export interface DraftEntry {
  key: string
  type: 'upload' | 'edit'
  movieId?: number
  data: MovieFormDraftData
  createdAt: number
  updatedAt: number
  expiresAt?: number
}

const UPLOAD_KEY = 'movie:upload'
const EDIT_KEY_PREFIX = 'movie:edit:'

// 默认编辑草稿过期时间（7天）
const DEFAULT_EDIT_TTL_MS = 1000 * 60 * 60 * 24 * 7

export const useDraftStore = defineStore('draft', () => {
  const state = reactive({
    drafts: {} as Record<string, DraftEntry>,
  })

  const buildEditKey = (movieId: number) => `${EDIT_KEY_PREFIX}${movieId}`

  const isExpired = (entry?: DraftEntry | null) => {
    if (!entry) return true
    if (entry.expiresAt && Date.now() > entry.expiresAt) return true
    return false
  }

  const purgeExpired = () => {
    const keys = Object.keys(state.drafts)
    for (const key of keys) {
      const entry = state.drafts[key]
      if (isExpired(entry)) {
        delete state.drafts[key]
      }
    }
  }

  const getUploadDraft = (): DraftEntry | undefined => {
    purgeExpired()
    const entry = state.drafts[UPLOAD_KEY]
    return entry
  }

  const getEditDraft = (movieId: number): DraftEntry | undefined => {
    purgeExpired()
    const key = buildEditKey(movieId)
    const entry = state.drafts[key]
    if (isExpired(entry)) {
      delete state.drafts[key]
      return undefined
    }
    return entry
  }

  const saveUploadDraft = (data: MovieFormDraftData) => {
    const now = Date.now()
    state.drafts[UPLOAD_KEY] = {
      key: UPLOAD_KEY,
      type: 'upload',
      data: JSON.parse(JSON.stringify(data)),
      createdAt: state.drafts[UPLOAD_KEY]?.createdAt ?? now,
      updatedAt: now,
    }
  }

  const saveEditDraft = (movieId: number, data: MovieFormDraftData, ttlMs: number = DEFAULT_EDIT_TTL_MS) => {
    const now = Date.now()
    const key = buildEditKey(movieId)
    state.drafts[key] = {
      key,
      type: 'edit',
      movieId,
      data: JSON.parse(JSON.stringify(data)),
      createdAt: state.drafts[key]?.createdAt ?? now,
      updatedAt: now,
      expiresAt: now + ttlMs,
    }
  }

  const clearUploadDraft = () => {
    delete state.drafts[UPLOAD_KEY]
  }

  const clearEditDraft = (movieId: number) => {
    delete state.drafts[buildEditKey(movieId)]
  }

  // 启动时清理一次过期草稿
  purgeExpired()

  return {
    drafts: state.drafts,
    // 查询
    getUploadDraft,
    getEditDraft,
    // 保存
    saveUploadDraft,
    saveEditDraft,
    // 清理
    clearUploadDraft,
    clearEditDraft,
  }
}, {
  // 持久化到 localStorage
  persist: {
    key: 'fm_drafts_v1',
  }
})

